package com.itheima.mp.controller;


import cn.hutool.core.bean.BeanUtil;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.Result;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.service.IUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/user")
@Slf4j
@RequiredArgsConstructor//只会对一些需要初始化(final)的变量构造函数
public class UserController {

    private final IUserService userService;



    /**
     * 新增用户
     * @param userFormDTO
     * @return
     */
    @PostMapping
    public Result saveUser(@RequestBody UserFormDTO userFormDTO) {
        //把DTO拷贝到PO
        User user = BeanUtil.copyProperties(userFormDTO, User.class);
        //新增
        userService.save(user);
        return Result.success();
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result removeUser(@PathVariable Long id) {
        userService.removeById(id);
        return Result.success();
    }

    /**
     * 根据ID查询用户
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<UserVO> queryUserById(@PathVariable Long id) {
        return Result.success(userService.queryUserAndAddressById(id));
    }


    /**
     * 根据ID批量查询用户
     * @param ids
     * @return
     */
    @GetMapping
    public Result<List<UserVO>> getUser(@RequestParam("ids") List<Long> ids) {
        return Result.success(userService.queryUserAndAddressByIds(ids));
    }

    /**
     * 根据id扣减余额
     * @param id
     * @param money
     * @return
     */
    @PutMapping("/{id}/deduction/{money}")
    public Result deductionMoneyById(@PathVariable Long id, @PathVariable Integer money) {
        userService.deductionMoneyById(id,money);
        return Result.success();
    }

    /**
     * 复杂条件查询
     * @param userQuery
     * @return
     */
    @GetMapping("/list")
    public Result<List<UserVO>> queryUsers(UserQuery userQuery) {
        //查询用户ID
        List<User> list = userService.queryUsers(userQuery.getName(),userQuery.getStatus().getValue(),userQuery.getMinBalance(),userQuery.getMaxBalance());
        //把PO拷贝到Vo
       return Result.success(BeanUtil.copyToList(list,UserVO.class));

    }

    /**
     * 分页查询
     * @param userQuery
     * @return
     */
    @GetMapping("/page")
    public Result<PageDTO<UserVO>> queryUsersPage(UserQuery userQuery) {
        return userService.queryUsersPage(userQuery);
    }


}
